import orgnization from '@/models/orgnization';
import {s_saveMaterialUserDefine, s_getMaterialCategoryTree, s_getMaterialDocument, s_getMaterialUserDefine, s_getOrgTargetKeysGlobal, s_getOrgTransferData, s_saveAllocateOrgGlobal, s_saveMaterialInfo, s_saveUnitData, s_getBusinessCategoryTree, s_getBusinessDocument, s_saveBusinessInfo, s_getBusinessDefine, s_saveBusinessDefine, s_saveAdjustState, getCommTreeByXid, s_getBusDefine } from '@/services/basis';
import { getSelection } from '@/services/selections';
import { ActionType, ProCard, ProColumns, ProForm, ProFormDatePicker, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText, ProTable } from '@ant-design/pro-components';
import { useModel, useRequest } from '@umijs/max';
import {Table, Card, theme,Row,Col,Tree, Space, Button, Form, Input, Modal, Radio, Select, DatePicker, Drawer, Transfer, Divider, Checkbox, Tabs, TabsProps, message} from 'antd';
import  { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import moment from 'moment';
import React, { useRef, useState } from 'react';

//客商分类组件
function CategoryTree({treeData,getBusiness}){
  return ( 
        <Tree treeData={treeData} defaultExpandAll  blockNode={true}
        onClick={(e,node)=>getBusiness(node)}
  />);
};

//客商档案表组件
function BusinessTable({tdata,setBusinessCode,table_ref}){
   interface DataType{
       id:number,  
       code:string,
       name:string,
       scode:string,
       category_code:string,
       credit_code:string,
       address:string,
       representor:string,
       capital:number,
       contactor:string,
       phone:string,
       email:string,
       business_code:string,
       state:number,
       status:number,
       operate_time:string,
       operater_code:string,
       //以下4个为视图中添加
       category_name:string,
       operater_name:string,
       x_id:number,
       cate_id:number,
    
   }
   const columns:ProColumns<DataType>[]=[
    {
      dataIndex:'category_name',
      title:'客商分类',
      width:'8%',
    },
    {
      dataIndex:'code',
      title:'客商编码',
      width:'6%',
    }, {
      dataIndex:'name',
      title:'名称',
      width:'16%',
    },{
      dataIndex:'scode',
      title:'简称',
      width:'8%',
    },
   {
      dataIndex:'credit_code',
      title:'统一社会信用代码',
      width:'10%',
    },{
      dataIndex:'representor',
      title:'法人代表',
      width:'8%',
    },{
      dataIndex:'capital',
      title:'注册资金/万元',
      width:'6%',
    },{
      dataIndex:'contactor',
      title:'联系人',
      width:'8%',
    },{
      dataIndex:'phone',
      title:'电话',
      width:'8%',
    },{
      dataIndex:'email',
      title:'电子邮箱',
      width:'8%',
    },{
         dataIndex:'business_name',
         title:'专管业务员',
         fixed:'right',
         width:'8%',
         },{
      dataIndex:'status',
      title:'状态',
      fixed:'right',
      width:'5%',
      render:(text)=>text===1?<>启用</>:<Space style={{color:'red'}}>{text===2?<>冻结</>:<>删除</>}</Space>,
    },
    {
      dataIndex:'state',
      title:'合作方式',
      render:(text)=>{
         var x='';
         switch(text){
          case 1: return <>正常</>;           
          case 2: return <>观察</>;           
          case 5: return <><Space style={{color:'red'}}>黑名单</Space></>;               
          case 9: return <>伙伴</>;
          };
        },
      fixed:'right',
      width:'6%',
    },
   ];

   return(
      <ProTable 
      dataSource={tdata} 
      columns={columns} 
      rowKey='id' 
      rowSelection={{
        type:'radio',
        onChange:(selectedKeys,selectedRows)=>setBusinessCode(selectedRows),
      }} 
      scroll={{x:'150%',y:360}}
      //onRow={(record)=>{return{onClick:()=>setBusinessCode(record.code)}}} 
      options={false}
      actionRef={table_ref}
      />
   );

}

//客商自定义项表，作为定义项--要调出所有自定义项，并勾选---暂时不处理客商自定义档案。
function MaterialUserDefine({udata,setUdata}){
 //监控自定义值的变化.type代表更新的字段：1 item_id,2 ismust,3 status
 function update(e:any,id:number,type:number){
  const x=udata.map((item)=>{
   // alert(e.target.value);
      if(item.userdefine_id===id){
          if(type===1)
              return {...item,item_code:e.target.checked?1:0};
          else if(type===2)
              return {...item,ismust:e.target.value};
          else
              return {...item,status:e.target.value};
      }
         
      else
         return item;
  });

  //更新新值到staate, 同步渲染新表格--关键
  setUdata(x);
}


   interface DataType{
    id:number,
    item_code:number,
    status:number,
    ismust:number,
    userdefine_id:number,
    code:string,
    name:string,
    //默认客商source_type=1
   } ;
   const columns:ColumnsType<DataType>=[
    {
      dataIndex:'userdefine_id',
      title:'ID',
    },
    {
      dataIndex:'code',
      title:'自定义项编码',
    },
    {
      dataIndex:'name',
      title:'自定义项名称',
    },
    {
      dataIndex:'item_code',
      title:'选择',
      render:(text,record)=>
      <Checkbox checked={text===1?true:false} onChange={(e)=>update(e,record.userdefine_id,1)}>
      </Checkbox>
      
    },
    {
      dataIndex:'ismust',
      title:'取值类型',
      render:(text,record)=><Radio.Group value={text} onChange={(e)=>update(e,record.userdefine_id,2)}>
                        <Radio value={1}>必填</Radio>
                        <Radio value={0}>非必填</Radio>
                     </Radio.Group>
    },
    {
      dataIndex:'status',
      title:'状态',
      render:(text,record)=><Radio.Group value={text} onChange={(e)=>update(e,record.userdefine_id,3)}>
                        <Radio value={1}>启用</Radio>
                        <Radio value={2}>冻结</Radio>
                        <Radio value={3}>非选项</Radio>
                    </Radio.Group>
    },
   ];  

  // alert('这是控件内：'+JSON.stringify(udata));
   return(
    <Table dataSource={udata} columns={columns} rowKey='code' rowSelection={{type:'radio'}}
    //onRow={(record)=>{return{onClick:()=>setUdata(record)}}}
    />
   );
}


const Welcome: React.FC = () => {
  const [selectedCategory,setSelectedCategory]=useState(0);   //选中的分类ID，其实可以合并到selectedNode,暂不处理。
  const [treeData,setTreeData]=useState();                        //分类树数据源
  const [selectedNode,setSelectedNode]=useState();            //选择的树节点
  const [tdata,setTdata]=useState();                               //档案表格数据源
  const [selectedRecords,setSelectedRecords]=useState([]);           //选中的客商记录，作为待处理用
  const [selectedKeys,setSelectedKeys]=useState<any[]>([]);//树选择的本级节点及下节点

  const [openInfo,setOpenInfo]=useState(false);//显示客商档案窗口
  const [openAllocate,setOpenAllocate]=useState(false);//显示客商分配窗口
  const [openDefine,setOpenDefine]=useState(false);//显示客商定义窗口--暂不处理
   

  const [etype,setEtype]=useState(0);   //1新增 0修改
  const [uintSelection,setUintSelection]=useState([]);

  const [cstate,setCstate]=useState(1);  //修改合作状态，1正常，2观察，5黑名单，9伙伴
  const [copen,setCopen]=useState(false);//调整合作状态的窗口是否显示
  //const [cform]=Form.useForm();//合作状态窗体---改为下方的cform_ref

  //const [orgtransfer,setOrgtransfer]=useState();//穿梭框数据源
  const [orgtargetkeys,setOrgtargetkeys]=useState([]);//穿梭框的已选中值

   //定义客商自定义项--此下暂不处理
   const [udata,setUdata]=useState([]);
   //客商管理中，选中的组织，用于带出对应的定义信息
   const [defineOrg,setDefineOrg]=useState();
    //表单下接组件数据源
    const [businessSelection,setBusinessSelection]=useState([]);
    const [orgSelection,setOrgSelection]=useState([]);


   const mtable_ref=useRef<ActionType>();//主表引用
   const cform_ref=useRef<ProFormInstance>();//合作窗体引用
   const eform_ref=useRef<ProFormInstance>();//客商编辑窗体引用
   const dform_ref=useRef<ProFormInstance>();//客商类型窗体

   
  //获取选择项：操作员，主辅计量单位--以下暂不处理
  const userdata=useModel('getUser');
  const unitdata=useModel('getUnit');
  const orgdata=useModel('getOrg');

    //在MODEL中,定义FORM供调用
    const orgtransfer=useModel('getOrgTransfer');//角色分配的组织穿梭框数据源--直接使用

 //此处创建一个生成树的通用方法，通过传入表名和X_ID值
 useRequest(()=>getCommTreeByXid({x_id:1,source_table:'business_category'}),{  
  onSuccess:(data:any)=>setTreeData(data),
});

  //获取客商档案表
  useRequest(()=>s_getBusinessDocument({x_id:1,cate_id:[],id:0}),{
         onSuccess:(data:any)=>{
          //  alert(JSON.stringify(data));
            setTdata(data);
         },
     }
  );

  //获取业务员下拉列表
useRequest(()=>getSelection({source:'base_person',x_id:1,id:0}),{
  onSuccess:(data:any)=>{
    const x=data.map((item:any)=>({value:item.id,label:item.code.concat(' ',item.name)}));
    setBusinessSelection(x);
  }
});

  //获取组织下拉列表--仅已分配的组织，加个type
  //useRequest(()=>getSelection({source:'base_organization',x_id:1,id:0}),{
  //   onSuccess:(data:any)=>{
  //    const y=data.map((item:any)=>({value:item.id,label:item.code.concat(' ',item.name)}));
   //   setOrgSelection(y);
   // }
  //});

 //根据左侧选择的类别，右侧表格显示明细--注意：此处传入的是树节点node(key,title) 
  //---先取本节点及下级节点值，再共同选---------------------------------------------开始-----------------
  var arr:any[]=[];
   //定义一个递归函数，获取选中节点下的所有key
   function getNodeKeys(node:{key:any,title:any,children:any[]}){
        if(node.children.length>0)
              node.children.map((item:any)=>{
                 arr.push(item.key);
                 if(item.children.length>0){
                      arr.push(getNodeKeys(item));
                 }
             });
      }

  async function getBusiness(node:any){
     // alert( (curCategory));
      setSelectedRecords([]);
      setSelectedCategory(node.key);
      setSelectedNode(node);
     
     arr=[];//先置为空，再取数据
     arr.push(node.key);
     getNodeKeys(node);
     setSelectedKeys(arr.filter((item)=>item!=null));//当前选中的组织的所有下级ID

     const x=await s_getBusinessDocument({x_id:1,cate_id:arr,id:0});
     //alert(JSON.stringify(x.data[0]));
     setTdata(x.data);
     mtable_ref.current?.reset?.();
     
  }
 //---先取本节点及下级节点值，再共同选---------------------------------------------结束-----------------

  //新增客商信息
  async function addBusinessInfo(){
    if(selectedCategory===0)
       message.warning('请先选择客商分类。');
    else{
       setEtype(1);
       //根据选
        //参数source_type:1为物料，2为客商（暂未使用）
       //const x=await s_getMaterialUserDefine({x_id:1,source_type:1,item_id:0}); //暂不处理自定义项 

      //物料自由项
       //setUdata(x.data[0]);
       setOpenInfo(true);
    }
}

//编辑客商信息
async function editBusinessInfo(){
  if(selectedRecords.length===0)
      message.warning('请先选择要修改的客商。');
   else{
     setEtype(0);
      
   //新增：编辑物料自由项
    //const m=await s_getMaterialUserDefine({x_id:1,source_type:1,item_id:selectedRecords[0]?.id}); //暂不处理自定义项 
    // alert(JSON.stringify(m.data[0]));
   // setUdata(m.data[0]);
    setOpenInfo(true);
   };
}

  //保存客商编辑信息
  async function saveBusinessInfo(){
    //先取表单的数据，再保存。
    const fdata0=eform_ref.current?.getFieldsValue();
    const fdata={...fdata0,id:selectedRecords[0]?.id,cate_id:etype===1?selectedCategory:selectedRecords[0]?.cate_id,
                  operate_time:moment(moment(fdata0.operate_time).toDate()).format('YYYY-MM-DD HH:mm:ss')};
    //alert('保存内容：'+JSON.stringify(fdata));
    //调用远程服务保存//保存基本信息    
    const x=await s_saveBusinessInfo({x_id:1,operater_id:1,etype,fdata});
    //保存自定义信息
    // alert(JSON.stringify(selectedRecords[0]));
   // const y=await s_saveMaterialUserDefine({x_id:1,operater_id:1,item_id:selectedRecords[0]?.id,fdata:udata}); 
               
    if(x.success){
       message.success('数据保存成功。');
       setOpenInfo(false);
       setTdata(x.data);
      // setUdata(y.data);
       //更新物料档案表
       mtable_ref.current?.reset?.();
     }
     else
       message.error('数据保存失败，请检查。');
 }

 
  //定义窗体引用
  const [formInfo]=Form.useForm();      //客商信息
  const [formAllocate]=Form.useForm();  //客商分配
  const [formDefine]=Form.useForm();    //客商定义
   
  //调用组织分配的界面
  async function allocateOrg(){
    if(selectedRecords.length===0)
        message.warning('请先选择要分配的物料。');
    else{
       const y=await s_getOrgTargetKeysGlobal({x_id:1,item_type:1,item_id:selectedRecords[0]?.id}); //---通用---
       const y0=y.data.map((item:any)=>item.id);
       setOrgtargetkeys(y0);
       setOpenAllocate(true)
     }
  }

  //保存组织分配
  async function saveAllocateOrgRole(){
    const x=await s_saveAllocateOrgGlobal(
         {x_id:1,operater_id:1,item_type:1,item_id:selectedRecords[0]?.id,fdata:orgtargetkeys});
    if(x.success){
      message.success('数据保存成功。');
      setOpenAllocate(false);
      
    }
    else
      message.error('数据保存失败，请检查');
  }
  
  
  //定义客商详细信息标签，以Tabs显示
  const items:TabsProps['items']=[
    {
      key:'1',
      label:'基本信息',
      children:<>
       <ProForm formRef={eform_ref}  name='eform' 
        submitter={{
          resetButtonProps:{style:{display:'none'}},
          submitButtonProps:{style:{display:'none'}},
        }}
        initialValues={etype===0?{...selectedRecords[0]}
                 :{status:1,operate_time:moment().toDate(),
                    category_code:selectedNode?.title.substring(0,selectedNode?.title.indexOf(' ')),
                    category_name:selectedNode?.title.substring(selectedNode?.title.indexOf(' ')),
                 }}
       >
           <Row gutter={8}>
            <Col span={8}>
            <ProFormText name='category_code' label='分类编码' disabled={true} width={300}/>
            <ProFormText name='category_name' label='分类名称' disabled={true} width={300}/>
            <ProFormText name='code' label='客商编码' width={300}/>
            <ProFormText name='name' label='客商名称' width={300}/>
            <ProFormText name='scode' label='简称' width={300}/>
          </Col>
          <Col span={8}>
            <ProFormText name='credit_code' label='统一社会信用代码' width={300}/>
            <ProFormText name='capital' label='注册资金/万元' width={300}/>
            <ProFormText name='representor' label='法人代表' width={300}/>
            <ProFormText name='contactor' label='联系人' width={300}/>
          <ProFormText name='email' label='电子邮件' width={300}/>
         </Col>
          <Col span={8}>
          <ProFormText name='phone' label='电话' width={300}/>
          <ProFormText name='address' label='地址' width={300}/>
          <ProFormSelect name='business_id' label='专管业务员' width={300}
              request={async ()=>businessSelection}
          />
           <ProFormRadio.Group name='status' label='状态' 
              options={[{value:1,label:'启用'},{value:2,label:'停用'},{value:3,label:'删除'}]}
              width={300}/>
          <ProFormDatePicker name='operate_time' label='操作时间' width={300}/>
          <ProFormText name='operater_code' label='操作人' width={300}/>
          </Col>
          </Row>
          
         </ProForm>
      </>
    },
   // {
   //   key:'2',
   //   label:'自定义项',
   //   children:<>
     //     <MaterialUserDefine udata={udata} setUdata={setUdata}/>
    //  </>
   // }
  ];

  //客商管理：定义客商的供应商、客户属性，未来添加自定义信息。。。业务信息在各自的功能模块里，另行添加
  async function businessDefine(){
     //先查询是否有记录，显示已分配的结果
     if(selectedRecords.length===0)
        message.warning('请先选择对应的客商。');
     else{  
       //formDefine.setFieldsValue({isvendor:undefined,iscustomer:undefined});  
       //在窗体打开时，进行初始化 
       setOpenDefine(true);}
  }

  //客商管理：保存定义的信息。目前只保存供应商、客户分类定义
  async function saveBusinessDefine(){
    const fdata=dform_ref.current?.getFieldsValue();
    //alert(JSON.stringify(fdata));
    if((fdata.isvendor===undefined&&fdata.iscustomer===undefined)||fdata.org_id===undefined)
       message.error('组织必选，且供应商和客户至少选择一项，请检查');
    else{
       const x=await s_saveBusinessDefine({operater_id:1,fdata:{...fdata,item_id:selectedRecords[0].id}});
       if(x.success)
       {
            message.success('数据保存成功。');
           //  setOpenDefine(false);
       }else
          message.error('数据保存失败，请检查。');
   }
}

  //在客商管理中，选中不同的组织时，带出定义的客商信息
  async function getDefineOrg(org_id:any){
     dform_ref.current?.resetFields(['iscustomer','isvendor']);
     setDefineOrg(org_id);
     const x0=await s_getBusinessDefine({org_id,item_id:selectedRecords[0].id});
    //  alert(JSON.stringify(x0.data));
        if(x0.data.length>0){
             const x=x0.data[0];
             dform_ref.current?.setFieldsValue({isvendor:x.isvendor,iscustomer:x.iscustomer});
        }
   }

//获取当前的记录，并修改state为相应的等级。1正常，2观察，5黑名单，9伙伴
async function adjustState(){
    if(selectedRecords.length===0)
      message.warning('请先选择要调整的供应商。');
    else{
     // cform_ref.current?.resetFields();
      //const x=tdata.filter((item)=>item.code===selectedCode);
     // alert(JSON.stringify(x));
      //cform.setFieldsValue({state:x[0].state});
       setCopen(true);
      }
    }
    
//保存合作等级
   async function saveAdjustState(){
    //获取当前的记录，并修改state为相应的等级。1正常，2观察，5黑名单，9伙伴
      const fdata=cform_ref.current?.getFieldsValue();
      const x=await s_saveAdjustState({item_id:selectedRecords[0]?.id,state:fdata.state});
      if(x.success){
          message.success('数据保存成功。');
          setCopen(false);
          setCstate(fdata.state);
          //更新表格状态--因只更新了一行，所以直接对数据源进行更新，不另加载
          setTdata(tdata?.map((item:any)=>{
              if(item.id===selectedRecords[0]?.id)
                  return {...item,state:fdata.state};
              else
                  return item;
           }));

          mtable_ref.current?.reset?.();
          setSelectedRecords([]);
     }
      else
        message.warning('数据保存失败，请检查。');
    }
    
//选中客商档案表格时，更新state
async function getSelectRecords(records:any){
   setSelectedRecords(records);

    //更新对应的已分配组织
     const y0=await getSelection({source:'base_organization',x_id:1,id:records[0]?.id,type:'businessallocateorg'});
     const y=y0.data.map((item:any)=>({value:item.id,label:item.code.concat(' ',item.name)}));
     setOrgSelection(y);
}

  return<>
     <Row gutter={10}>
     <Col  span={6}>
     <Card title='客商分类' style={{height:700}}>
        {JSON.stringify(selectedCategory)}
         <CategoryTree treeData={treeData} getBusiness={getBusiness}/>
     </Card>
     </Col>
     <Col  span={18}>
      <Card title='客商基础档案'  style={{height:700}} id='drawer_id'
      extra={<Space size='large'>
      <Button  onClick={()=>addBusinessInfo()}>新增档案</Button>
      <Button  onClick={()=>editBusinessInfo()}>修改档案</Button>
      <Button  onClick={()=>allocateOrg()}>分配组织</Button>
      <Button onClick={()=>adjustState()}>调整合作状态</Button>
      <Button  onClick={()=>businessDefine()}>客商管理</Button>
      
      </Space>}
      >
        {JSON.stringify(selectedRecords)}
       <BusinessTable tdata={tdata} setBusinessCode={getSelectRecords} table_ref={mtable_ref}/>

       <Drawer title='分配组织' placement='bottom' open={openAllocate} destroyOnClose={true} closable={true}
        onClose={()=>setOpenAllocate(false)}   getContainer={false}
        extra={ <Button onClick={()=>saveAllocateOrgRole()}>保存</Button>}>  
            <Transfer 
            titles={['未分配组织','已分配组织']}
            dataSource={orgtransfer}
            targetKeys={orgtargetkeys}
            render={(item:any)=>item.title}
            onChange={(tkeys:any,direction,mkeys)=>setOrgtargetkeys(tkeys)}            
            />
      </Drawer>

      <Drawer title='客商管理' placement='bottom' open={openDefine}  
        onClose={()=>setOpenDefine(false)}   getContainer={false} destroyOnClose={true}
        extra={ <Button onClick={()=>saveBusinessDefine()}>保存</Button>}>  
            
             <ProForm name='dform' formRef={dform_ref} 
             submitter={{
              resetButtonProps:{style:{display:'none'}},
              submitButtonProps:{style:{display:'none'}},
             }}
             onFieldsChange={async (fields)=>{
              if(fields[0].name[0]==='org_id'){
                 dform_ref.current?.resetFields(['isvendor','iscustomer']);
                 var x=await s_getBusDefine({org_id:fields[0].value,item_id:selectedRecords[0]?.id});
                 if(x.data!=undefined)
                   dform_ref.current?.setFieldsValue({isvendor:x.data.isvendor,iscustomer:x.data.iscustomer});
            }
             }}
             >
              <ProFormSelect name='org_id' label='组织'   width={300}
                request={async ()=>orgSelection}
              />
               <Row gutter={16}>
                  <Col span={12}>
                  <ProFormRadio.Group name='isvendor' label='是否供应商' rules={[{required:true,message:'必须选择项'}]}
                  options={[{value:1,label:'是'},{value:0,label:'否'}]}   width={300}/>
               </Col>
               <Col span={12}>
               <ProFormRadio.Group name='iscustomer' label='是否客户'  rules={[{required:true,message:'必须选择项'}]} 
                  options={[{value:1,label:'是'},{value:0,label:'否'}]}  width={300}/>
               </Col>
               </Row>
             
             </ProForm>
      </Drawer>

      </Card>
      </Col>
     </Row>

     <Modal title='客商维护' open={openInfo}  width='88%'   maskClosable={false} okButtonProps={{hidden:true}}
       cancelButtonProps={{hidden:true}} destroyOnClose={true} closable={true}  style={{top:19}}
      >
      <ProCard extra={<Space size='large'>
         <Button onClick={()=>saveBusinessInfo()}>保存</Button>
         <Button onClick={()=>setOpenInfo(false)}>取消</Button>
      </Space>}>
        <Tabs items={items} type='card' style={{height:520}}/>
        </ProCard>
     </Modal>

   
     <Modal open={copen}  title='调整合作状态' destroyOnClose={true} closable={true} maskClosable={false}
        width='36%' okButtonProps={{hidden:true}} cancelButtonProps={{hidden:true}}>
          <ProCard extra={<Space size='large'>
             <Button onClick={()=>saveAdjustState()}>保存</Button>
             <Button onClick={()=>setCopen(false)}>取消</Button>
          </Space>}>
        <ProForm name='cform' formRef={cform_ref} 
          submitter={{
            resetButtonProps:{style:{display:'none'}},
            submitButtonProps:{style:{display:'none'}},
          }}
          // initialValues={{state:2}}
          initialValues={{state:selectedRecords[0]?.state}}
        >
          <ProFormRadio.Group name='state' label='合作状态' 
            options={[{value:1,label:'正常'},{value:2,label:'观察'},{value:5,label:'黑名单'},{value:9,label:'伙伴'}]}
              width={300}/>
        </ProForm>
        </ProCard>
     </Modal>
     
  </>
};

export default Welcome;